using RockHopper.Common.Data;
using RockHopper.Common.Events;
using RockHopper.TrainingCalculator.WinRT.Utils;
using Windows.ApplicationModel;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;

namespace RockHopper.TrainingCalculator.WinRT.Controls
{
    public class VdotControl : Control
    {
        private Slider slider;
        private TextBlock textblock;
        private static readonly ISettingsRepository settingsRepository;

        public VdotControl()
        {
            DefaultStyleKey = typeof(VdotControl);
        }

        static VdotControl()
        {
            if (!DesignMode.DesignModeEnabled)
            {
                settingsRepository = Global.Container.Resolve<ISettingsRepository>();
            }   
        }

        protected override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            slider = (Slider)GetTemplateChild("SliderPart");
            textblock = (TextBlock)GetTemplateChild("TextBlockPart");
            
            slider.Value = settingsRepository.Vdot;
            textblock.Text = slider.Value.RoundToString();
            slider.ValueChanged += OnSliderValueChanged;

            DomainEvents.VdotChanged += OnVdotChanged;
        }

        private void OnSliderValueChanged(object sender, RangeBaseValueChangedEventArgs args)
        {
            settingsRepository.Vdot = args.NewValue;
            textblock.Text = args.NewValue.RoundToString();
            DomainEvents.RaiseVdotChanged(this, new VdotChangedEventArgs(args.NewValue));
        }

        private void OnVdotChanged(object sender, VdotChangedEventArgs args)
        {
            if (sender == this) return;

            slider.Value = args.Vdot;
            textblock.Text = args.Vdot.RoundToString();
        }
    }
}